package com.common.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class RandomUtil {
	public static String createRandomCode(String name){
		Integer number = (int)((Math.random()*9+1)*100);
		 StringBuffer pybf = new StringBuffer();
		 if(name != null){
	         char[] arr = name.toCharArray();   
	         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();   
	         defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);   
	         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);   
	         for (int i = 0; i < arr.length; i++) {   
	                 if (arr[i] > 128) {   
	                         try {   
	                                 pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);   
	                         } catch (BadHanyuPinyinOutputFormatCombination e) {   
	                                 e.printStackTrace();   
	                         }   
	                 } else {   
	                         pybf.append(arr[i]);   
	                 }   
	         }   
		 }
         return pybf.toString() + number;   
	}
	
	/**
	 * 随机1位大写字母+uid5位+rand(二位数)+time(月日时分8位),
	 * 然后截取16位出来生成比如T132-0161-2052-3091,
	 */
	public static String getRandomCode(){
		//随机任意一位大写字母1
		String word=getFirstWordForPersonCode();
		//截取uuid5
		String uuid=StringUtil.getUUID().substring(1, 6);
		//随机2为数字
		String num=getRandom(2);
		//当前日期的月日时分8
		String time=getTimeForPersonCode();
		//生成code
		String s=word+uuid.substring(0, 3)+uuid.substring(3,5)+num+time.substring(0, 4)+time.substring(4,8);
		return s;
	}
	
	/**
	 * 当前时间的月日时分
	 */
	public static String getTimeForPersonCode(){
		Date date=new Date();
		DateFormat format=new SimpleDateFormat("MMddHHmm");
		String time=format.format(date);
		return time;
	}
	
	/**
	 * 随机一位大写字母
	 */
	public static String getFirstWordForPersonCode(){
		final int maxNum = 26;
		int i;
		Random r = new Random();
		String[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
				"T", "U", "V", "W", "X", "Y", "Z"};
		i = Math.abs(r.nextInt(maxNum));
		String word=str[i];
		return word;
	}
	
	/**
	 * 生成多位随机数
	 * @param len 随机数的长度
	 */
	public static String getRandom(int len){
		String sb="";
		for(int index=0;index<len;index++) {
			String s = String.valueOf((int)(10*(Math.random())));
			sb+=s;
		}
		return sb;
	}
	
}
